import com.mysql.cj.Session;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取用户名和密码
        req.setCharacterEncoding("utf-8");
        String userName=req.getParameter("userName");
        String password=req.getParameter("password");
        //注意空引用
        if(userName==null||password==null||userName.equals("")||password.equals("")){
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("用户名或密码为空");
            return;
        }
        UserDao userDao=new UserDao();
        User user=userDao.selectByName(userName);
        if(user==null || !user.getPassword().equals(password)){
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("用户名或密码错误");
            return;
        }
        //登录成功，创建会话保存
        HttpSession session=req.getSession(true);
        session.setAttribute("user",user);
        //302重定向报文
        resp.sendRedirect("blog_list.html");

    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session=req.getSession(false);
        //无会话，未登录
        if(session==null){
            resp.setStatus(403);
        }else {
            //如果user不存在，未登录
            User user= (User) session.getAttribute("user");
            if(user==null){
                resp.setStatus(403);
            }else {
                resp.setStatus(200);
            }
        }


    }
}
